<%@ page language="java" import="java.util.*" import ="edu.colorado.karl.login.AccountManager"%>
<%@ page import="edu.colorado.karl.login.Authenticate"%>

<%@ include file = "header.jspf" %>

<link rel="Stylesheet" type="text/css" media="Screen" charset="utf-8" href="css/common.css"/>

<html>
<title>saving changes...</title>
<body>

<%
AccountManager am = AccountManager.getAccountManager();
String cancelNewAccount = request.getParameter("cancel_new");
boolean tempbool = false;
String tempstr2;

userList = am.getUsers();
tempstr = "";


//check if a new account is being added
if(am.getAddNew())
{
  tempstr = request.getParameter("new_acct_name");

  //check whether the new user is an administrator
  if(request.getParameter("admin_new") != null)
  {
    tempbool = true;
  }
  else
  {
    tempbool = false;
  }

  

  if(!tempstr.matches("\\p{Alnum}+") || tempstr.length() > 12 || tempstr.length() < 6)
  {
    tempstr = null;

    %>

    <br>Error, username must consist of 6 - 12 alphanumeric characters.
    <br>Redirecting to account manager in 5 seconds...
    <meta http-equiv=REFRESH content=5;url=acctmanager.jsp>

    <%

  }
  
  //add the new user to the database and return to the account manager
  if(tempstr != null && cancelNewAccount == null)
  {
    am.addUser(tempstr,tempbool);
    am.setAddNew(false);

    %>

    <br>New account created successfully.
    <br>Redirecting to account manager in 5 seconds...
    <meta http-equiv=REFRESH content=5;url=acctmanager.jsp>

    <%
  }

  else
  {
    am.setAddNew(false);
  }
}

//i = 0 is the original admin account that can't be changed or removed
for(i = 1; i < userList.size(); i++)
{
  //stores the current username
  tempstr2 = (String)userList.get(i);

  //stores the current account modification string
  tempstr = "admin_change_" + tempstr2;

  if(request.getParameter(tempstr) != null)
  {
    if(!a.userIsAdmin(tempstr2))
    {
      //make this user an administrator
      am.grantAdminAccess(tempstr2);
    }
  }
  else
  {
    if(a.userIsAdmin(tempstr2))
    {
      //revoke this user's administrative rights
      am.revokeAdminAccess(tempstr2);
    }
  }

  tempstr = "remove_" + tempstr2;
  if(request.getParameter(tempstr) != null)
  {
    //delete this user
    am.removeUser(tempstr2);
  }
}

if(tempstr != null)
{
%>

  <br>Changes were saved successfully.
  <br>Redirecting to account manager in 2 seconds...
  <meta http-equiv=REFRESH content=2;url=acctmanager.jsp>

<%
}

%>

</body>
</html>